package com.qire.manhua.model.viewModel.impl;

import android.view.View;

import com.qire.common.basic.DateUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.AbsBringDialogViewModel;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.R;
import com.qire.manhua.controller.ComicDetailDirectoryController;
import com.qire.manhua.databinding.LayoutComicDetailDirectoryItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicBookEntity.DirectoryInfo;
import com.qire.manhua.model.enumeration.FreeType;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

public class ComicDetailDirectoryViewModel extends AbsBringDialogViewModel {

    private final ArrayList<ComicDetailDirectoryItemViewModel> directoryItemList = ListUtil.newArrayList();
    private final SummerRecyclerBindAdapter<ComicDetailDirectoryItemViewModel> directoryAdapter = new SummerRecyclerBindAdapter<>(directoryItemList);

    private ComicBookEntity comicBookEntity;
    private ComicDetailViewModel detailViewModel;

    private boolean isAscSort = true;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(ComicDetailDirectoryController controller) {
        this.directoryAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        this.comicBookEntity = null;
        this.detailViewModel = null;
        this.directoryAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    public void setComicDetail(ComicDetailViewModel detailViewModel) {
        this.detailViewModel = detailViewModel;
    }

    public void loadComicBookEntity(ComicBookEntity comicBookEntity) {
        if(comicBookEntity == null) {
            return;
        }
        this.comicBookEntity = comicBookEntity;

        if(ListUtil.notEmpty(directoryItemList)) {
            directoryItemList.clear();
        }

        for(DirectoryInfo directoryInfo : comicBookEntity.directoryInfoList) {
            if(directoryInfo == null || directoryInfo.canNotShow()) {
                return;
            }
            directoryItemList.add(new ComicDetailDirectoryItemViewModel(directoryInfo));
        }
        if(!isAscSort) {
            // isAscSort 默认是升序排列为true，如果排序被改变则为false，
            // loadComicBookEntity方法可以视作为始终升序排列的列表，所以如果排序改变过这里需要逆序排一次
            reverseSort();
        }
        refreshDirectoryAdapter();

        setAllChapterCountText(String.format("全部章节（%s）", directoryItemList.size()));
    }

    public ComicBookEntity comicBookEntity() {
        return comicBookEntity;
    }

    public void refreshReadChapterInfo() {
        detailViewModel.refreshReadChapterInfo();
    }
    public void unlockChapterByAd(int chapterId) {
        detailViewModel.unlockChapterByAd(chapterId);
    }
    public void unlockChapterByBuy(int chapterId, String  chapterPrice, String  paymentType) {
        detailViewModel.unlockChapterByBuy(chapterId, chapterPrice, paymentType);
    }

    private void reverseSort() {
        ListUtil.reverse(directoryItemList);
    }

    private void refreshDirectoryAdapter() {
        directoryAdapter.notifyDataSetChanged();
    }

    public void toggleSort() {
        isAscSort = !isAscSort;
        reverseSort();
        refreshDirectoryAdapter();
        set("sortPageNumber", isAscSort ? 0 : 1);
    }
    public void setAllChapterCountText(CharSequence allChapterCountText) {
        set("allChapterCountText", allChapterCountText);
    }

    public MutableLiveData<CharSequence> getAllChapterCountText() {
        return get("allChapterCountText");
    }

    public MutableLiveData<Integer> getSortPageNumber() {
        return get("sortPageNumber");
    }

    public Adapter getDirectoryAdapter() {
        return directoryAdapter;
    }

    public LayoutManager getLayoutManager() {
        return new LinearLayoutManager(null, LinearLayoutManager.VERTICAL, false);
    }

    @AdapterEntityBind(viewRid = R.layout.layout_comic_detail_directory_item)
    public class ComicDetailDirectoryItemViewModel extends BaseObservable implements AutoVariable<LayoutComicDetailDirectoryItemBinding> {

        public final DirectoryInfo directoryInfo;

        public ComicDetailDirectoryItemViewModel(DirectoryInfo directoryInfo) {
            this.directoryInfo = directoryInfo;
        }

        @Override
        public void bindVariable(LayoutComicDetailDirectoryItemBinding viewBind) {
            viewBind.setComicDetailDirectoryItemViewModel(this);
        }


        @Bindable
        public String getCoverImgUrl() {
            return directoryInfo.chapterCover;
        }
        @Bindable
        public int getCoverMaskVisible() {
            if(directoryInfo.notNeedBuy())
                return View.GONE;
            if(!directoryInfo.haveLock())
                return View.GONE;
            return View.VISIBLE;
        }
        @Bindable
        public int getAdLockVisible() {
            if(directoryInfo.notNeedBuy())
                return View.GONE;
            if(directoryInfo.isVipFree && UserEntity.self.isVip())
                return View.GONE;
            if(!directoryInfo.haveLock())
                return View.GONE;
            if(!directoryInfo.canUnlockedByAd())
                return View.GONE;

            return View.VISIBLE;
        }

        @Bindable
        public int getVipFreeBuoyVisible() {
            if(directoryInfo.canUnlockedByAd() && !UserEntity.self.isVip())
                return View.GONE;
            return directoryInfo.isVipFree ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public CharSequence getVipFreeBuoyText() {
            return comicBookEntity.lockInfo().bookFreeType == FreeType.VipFree ? "会员免费" : "会员限免";
        }

        @Bindable
        public int getLockStatusIconRes() {
            // 默认为免费章节，不需要解锁。
            if(directoryInfo.notNeedBuy()) {
                return 0;
            }
            if(!directoryInfo.haveLock()) {
                return R.drawable.app_comic_detail_directory_icon_unlocked;
            }
            // 可以广告解锁的
            if(directoryInfo.canUnlockedByAd()) {
                return 0;
            }

            return R.drawable.app_comic_detail_directory_icon_locked;
        }

        @Bindable
        public CharSequence getChapterText() {
            return directoryInfo.chapterName;
        }

        @Bindable
        public CharSequence getUpdateDate() {
            return directoryInfo.updateDate;
        }

        @Bindable
        public CharSequence getLikeCount() {
            return StringUtil.toSymbol(directoryInfo.likeCount);
        }

        @Bindable
        public CharSequence getUnlockInfo() {
            String unlockedExpiredTime = directoryInfo.getUnlockedExpiredTime();
            if (directoryInfo.isVipFree && UserEntity.self.isVip()) {
                return "";
            }

            if(StringUtil.isEmpty(unlockedExpiredTime)) {
                return "";
            }

            return  "解锁剩余" + DateUtil.yMdHms.toSomeday(unlockedExpiredTime).autoFormat();
        }

    }

}
